package com.vito.framework.system.dict.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vito.framework.base.controller.BaseController;
import com.vito.framework.base.exception.CommonException;
import com.vito.framework.cache.CacheKeys;
import com.vito.framework.system.dict.model.SysDict;
import com.vito.framework.system.dict.service.DictManageService;
import com.vito.framework.system.dict.service.DictService;
import com.vito.support.ApiResponse;
import com.vito.support.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***************************************************************
 * Name:        DictManageController.java
 * Create At:   2017年8月18日
 * Module:
 * Description: [参数配置管理]
 * @author ztshan
 * ------------------------------------------------------------
 * 修改历史
 * 序号         日期                       修改人               修改原因
 * 1    2017年8月18日      ztshan
 * 2
 ***********************************************************/
@RestController
@RequestMapping("${adminPath}/dict")
public class DictManageController extends BaseController {

    @Autowired
    public DictManageService dictManageService;
    @Autowired
    public DictService dictService;

    /**
     * Author:dihl
     * Create At:2010-04-22
     * Description: [系统参数管理-查询参数列表]
     *
     * @return String
     * @throws Exception
     */

    @PostMapping(value = "list", consumes = "application/json;charset=UTF-8")
    public ApiResponse list(HttpServletRequest request, @RequestBody JSONObject params) {
        Map<String, Object> paramMap = super.getParamMap(request, params);

        if (null == paramMap) {
            return ApiResponse.of(ResultEnum.PARAMS_INVALID);
        }

        int pageCount;
        int page = params.getIntValue("page");
        int limit = params.getIntValue("limit");
        try {
            paramMap.put("siId", paramMap.get("orgId"));
            paramMap.put("param_keyword", params.getString("param_keyword"));
            paramMap.put("param_curpage", page);
            paramMap.put("param_ipagecount", limit);
            IPage<SysDict> resultList = dictManageService.getDictManageList(paramMap);
            return ApiResponse.ofPage(resultList);
        } catch (CommonException e) {
            return ApiResponse.of(e);
        }
    }

    /**
     * Author:miaowenqiang
     * Create At:2012-07-11
     * Description: [系统参数管理-保存数据]
     *
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "add", consumes = "application/json;charset=UTF-8")
    public ApiResponse add(HttpServletRequest request, @RequestBody JSONObject params) {
        Map<String, Object> paramMap = super.getParamMap(request, params);
        if (null == paramMap) {
            return ApiResponse.of(ResultEnum.PARAMS_INVALID);
        }

        try {
            SysDict sysDict = new SysDict();
            JSONArray listArray = params.getJSONArray("list");
            String code = "";
            String name = "";
            String status = "";
            String sort = "";
            for (int i = 0; i < listArray.size(); i++) {
                JSONObject json = listArray.getJSONObject(i);
                code = code + json.getString("code1") == null ? "" : json.getString("code1") + ",";
                name = name + json.getString("name1") == null ? "" : json.getString("name1") + ",";
                status = status + json.getString("status") == null ? "" : json.getString("status") + ",";
                sort = sort + json.getString("sort1") == null ? "" : json.getString("sort1") + ",";
            }
            sysDict.setPtypeCode(params.getString("pcode"));
            sysDict.setPtypeName(params.getString("pname"));
            sysDict.setDictCode(code);
            sysDict.setDictName(name);
            sysDict.setStatus(status);
            sysDict.setSort(sort);
            dictManageService.addSave(sysDict);
            List<SysDict> list = dictManageService.list(new LambdaQueryWrapper<SysDict>().orderByAsc(SysDict::getSort));
            cacheUtil.put(CacheKeys.SYS_DICT, list);
            return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
            return ApiResponse.of(e);
        }
    }

    /**
     * Author:miaowenqiang
     * Create At:2012-07-12
     * Description: [系统参数管理-修改数据]
     *
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "get", consumes = "application/json;charset=UTF-8")
    public ApiResponse get(HttpServletRequest request, @RequestBody JSONObject params) {
        Map<String, Object> paramMap = super.getParamMap(request, params);
        if (null == paramMap) {
            return ApiResponse.of(ResultEnum.PARAMS_INVALID);
        }

        Map<String, Object> resMap = new HashMap<>();
        try {
            List<SysDict> resultList = dictManageService.list(new LambdaQueryWrapper<SysDict>().eq(SysDict::getPtypeCode, params.get("param_pcode")));
            resMap.put("resultList", resultList);
            resMap.put("baseBean", (resultList != null && resultList.size() > 0) ? resultList.get(0) : new SysDict());

            return ApiResponse.ok(resMap);
        } catch (CommonException e) {
            return ApiResponse.of(e);
        }
    }

    /**
     * Author:dihl
     * Create At:2012-07-12
     * Description: [系统参数设置-删除系统参数]
     *
     * @return String
     */
    @PostMapping(value = "delete", consumes = "application/json;charset=UTF-8")
    public ApiResponse delete(HttpServletRequest request, @RequestBody JSONObject params) {
        Map<String, Object> paramMap = super.getParamMap(request, params);
        if (null == paramMap) {
            return ApiResponse.of(ResultEnum.PARAMS_INVALID);
        }
        String pcode = params.getString("pcode");
        Integer dictId = params.getInteger("id");
        try {
            paramMap.put("dictId", dictId);
            if (pcode != null && pcode != "") {
                paramMap.put("pcode", pcode);
            }
            dictManageService.deleteDictManageList(paramMap);
            List<SysDict> list = dictManageService.list(new LambdaQueryWrapper<SysDict>().orderByAsc(SysDict::getSort));
            cacheUtil.put(CacheKeys.SYS_DICT, list);
            return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
            return ApiResponse.of(e);
        }
    }

    /**
     * Author:miaowenqiang
     * Create At:2012-07-12
     * Description: [系统参数管理-保存修改数据]
     *
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "edit", consumes = "application/json;charset=UTF-8")
    public ApiResponse edit(HttpServletRequest request, @RequestBody JSONObject params) {
        Map<String, Object> paramMap = super.getParamMap(request, params);
        if (null == paramMap) {
            return ApiResponse.of(ResultEnum.PARAMS_INVALID);
        }
        try {
            SysDict baseBean = new SysDict();
            JSONArray listArray = params.getJSONArray("list");
            String code = "";
            String name = "";
            String status = "";
            String sort = "";
            for (int i = 0; i < listArray.size(); i++) {
                JSONObject json = listArray.getJSONObject(i);
                code += json.getString("code1") == null ? "" : json.getString("code1") + ",";
                name += json.getString("name1") == null ? "" : json.getString("name1") + ",";
                status += json.getString("status1") == null ? "" : json.getString("status1") + ",";
                sort += json.getString("sort1") == null ? "" : json.getString("sort1") + ",";
            }
            baseBean.setPtypeCode(params.getString("pcode"));
            baseBean.setPtypeName(params.getString("pname"));
            baseBean.setDictCode(code);
            baseBean.setDictName(name);
            baseBean.setStatus(status);
            baseBean.setSort(sort);
            dictManageService.editSave(baseBean);
            List<SysDict> list = dictManageService.list(new LambdaQueryWrapper<SysDict>().orderByAsc(SysDict::getSort));
            cacheUtil.put(CacheKeys.SYS_DICT, list);

            return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
            return ApiResponse.of(e);
        }
    }

    @PostMapping(value = "getDictByType", consumes = "application/json;charset=UTF-8")
    public ApiResponse getDictByType(HttpServletRequest request, @RequestBody JSONObject params) {
        Map<String, Object> paramMap = super.getParamMap(request, params);
        if (null == paramMap) {
            return ApiResponse.of(ResultEnum.PARAMS_INVALID);
        }

        Map<String, Object> resMap = new HashMap<>();
        try {
            List<SysDict> result = dictService.getTypeList(params.getString("type"));
            resMap.put("result", result);
            return ApiResponse.ok(resMap);
        } catch (CommonException e) {
            return ApiResponse.of(e);
        }
    }
}
